package me.zhengjie.pay.rest;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.annotation.Log;
import me.zhengjie.annotation.rest.AnonymousPostMapping;
import me.zhengjie.business.domain.sup.Gsgl;
import me.zhengjie.business.service.GsglService;
import me.zhengjie.business.service.dto.RyglQueryCriteria;
import me.zhengjie.inter.service.MpZhsqService;
import me.zhengjie.mi.old.EasyGmUtils;
import me.zhengjie.pay.domain.PaidQueryCriteria;
import me.zhengjie.pay.domain.PayEnum;
import me.zhengjie.pay.service.UnPaidService;
import me.zhengjie.utils.HttpClientUtils;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.SecurityUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xiahongbo
 * @date 2022-07-21
 **/
@Slf4j
@RestController
@RequiredArgsConstructor
@Api(tags = "支付接口")
@RequestMapping("/api/pay")
public class PayController {


    private final UnPaidService unPaidService;

    private final GsglService gsglService;

    @ApiOperation("支付接口维护")
    @AnonymousPostMapping(produces = "application/json;charset=UTF-8")
    public ResponseEntity<Object> queryPay(@RequestBody JSONObject obj) {

        log.info("收到的参数 {}", obj);
        JSONObject object = obj.getJSONObject("strJson");

        // 将获取的json数据封装一层，然后在给返回
        JSONObject rs = new JSONObject();

        String tranCode = (String)object.get("TranCode");

        // 判断tranCode 是否有值
        if(StringUtils.isEmpty(tranCode)) {

            log.info("TranCode : {}", tranCode);

            JSONObject result = new JSONObject();
            result.put("TranCode", PayEnum.UnPaid.getCode());
            result.put("ResultCode", PayEnum.TranCodeNull.getCode());
            result.put("ErrorMsg", PayEnum.TranCodeNull.getDescription());

            return ResponseEntity.ok(result);
        }

        if (PayEnum.UnPaid.getCode().equals(tranCode)) { // 执行待缴费查询业务
            log.info("交易代码 : {}， 交易名称 : {}", PayEnum.UnPaid.getCode(), PayEnum.UnPaid.getDescription());
            rs = unPaidService.queryUnPaidInfo(object);
        } else if(PayEnum.SettleAccounts.getCode().equals(tranCode)) { // 执行结算业务
            log.info("交易代码 : {}， 交易名称 : {}", PayEnum.SettleAccounts.getCode(), PayEnum.SettleAccounts.getDescription());
            rs = unPaidService.settleAccounts(object);
        }
        log.info("返回值 {}", rs);

        return ResponseEntity.ok(rs);
    }

    @ApiOperation("退费")
    @GetMapping(value = "/refundPay")
    public ResponseEntity<Object> refundPay(@RequestParam String tranFlowNo, @RequestParam String type) {
        String url = "http://10.199.4.30:10080/ccyb_jjzh-chronic/clinic-refund-bus";
        String clientid="6266306ACCCFEA63";
        String plainString = tranFlowNo;
        byte[] prvkey = Base64.getDecoder().decode("ZfGn/WK9i6LjblYmJnr+lLhkXXNr8my9v95VWQYhJwc=");
        byte[] asig = EasyGmUtils.signSm3WithSm2(plainString.getBytes(StandardCharsets.UTF_8), clientid.getBytes(StandardCharsets.UTF_8), prvkey);
        String signstr=new String(Base64.getEncoder().encode(asig));

        // String parsms = "settlementId="+orderId+"&rollbackType=3&sign="+signstr;

        Map<String , String> params = new HashMap<>();

        params.put("settlementId", tranFlowNo);
        params.put("rollbackType", type);
        params.put("sign", signstr);

        log.info("请求地址 {}", url);
        log.info("退费参数 {}", params);

        String rs = HttpClientUtils.sendIOPost(url, params, null, Charset.forName("UTF-8"), null);
        log.info("返回值 {}", rs);
        return ResponseEntity.ok(rs);
    }

    @ApiOperation("结算查询（用于退费）")
    @GetMapping(value = "/refundList")
    public ResponseEntity<Object> refundList(PaidQueryCriteria criteria, Pageable pageable) {

        return new ResponseEntity<>(unPaidService.refundList(criteria.getBlurry(), pageable), HttpStatus.OK);
    }

    @ApiOperation("拨付单")
    @GetMapping(value = "/queryKb03")
    public ResponseEntity<Object> queryKb03(PaidQueryCriteria criteria, Pageable pageable) {
        Long userid = SecurityUtils.getCurrentUserId();
        Gsgl gsgl = gsglService.queryGsgl(userid);
        criteria.setAkb020(gsgl.getBisGsglYljgdm());
     //   criteria.setAkb020("1ZC1");
        return new ResponseEntity<>(unPaidService.queryKb03(criteria, pageable), HttpStatus.OK);
    }

}
